/**
 * 
 */
package com.example.demo.config;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.mysql.cj.jdbc.MysqlXADataSource;

/**
 * @author CJunGod 1038804380@qq.com
 *
 */
@Configuration
@MapperScan(basePackages = "com.example.demo.mapper",sqlSessionTemplateRef = 
"userSqlSessionTemplate")
public class UserDataSourceConfig {
	
	/**
	 * 创建user的Datasource 将我们的数据源统一的交给我们全局xa事务进行管理
	 * @return
	 * @throws SQLException 
	 */
	@Bean("userDataSource")
//	@ConfigurationProperties(prefix = "spring.datasource.user")
	public DataSource userDataSOurce(AtomikosConfig config) throws SQLException {
		//1.创建我们的xaDataSource
		MysqlXADataSource dataSource = new MysqlXADataSource();
		dataSource.setUrl(config.getUrl());
		dataSource.setUser(config.getUsername());
		dataSource.setPassword(config.getPassword());
		dataSource.setPinGlobalTxToPhysicalConnection(true);
		//2.注册到我们全局事务上面
		AtomikosDataSourceBean atomikosDataSourceBean = new AtomikosDataSourceBean();
		atomikosDataSourceBean.setXaDataSource(dataSource);
		
		return atomikosDataSourceBean;
	}
	
	/**
	 * 创建SqlSessionFactry
	 * @param dataSource
	 * @return
	 * @throws Exception
	 */
	@Bean("userSqlSessionFactry")
	public SqlSessionFactory userSqlSessionFactry(@Qualifier("userDataSource")DataSource dataSource) throws Exception {
		SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
		sessionFactoryBean.setDataSource(dataSource);
		return sessionFactoryBean.getObject();
	}
	
	/**
	 * 创建事务管理器
	 * @param dataSource
	 * @return
	 */
//	@Bean("userManager")
//	public DataSourceTransactionManager manager(@Qualifier("userDataSource")DataSource dataSource) {
//		return new DataSourceTransactionManager(dataSource);
//	}
	
	/**
	 * 创建模板
	 * @param sessionFactory
	 * @return
	 */
	@Bean("userSqlSessionTemplate")
	public SqlSessionTemplate userSqlSessionTemplate(
			@Qualifier("userSqlSessionFactry")SqlSessionFactory sessionFactory) {
		return new SqlSessionTemplate(sessionFactory);
	}

}
